package org.mindrive.system.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public class ConvertUtil {
	/**
	 * 分割字符串
	 * 
	 * @param text
	 * @return
	 */
	public static List<String> split(String text) {
		List<String> result = new ArrayList<String>();
		if (text != null && !"".equals(text)) {
			String[] texts = text.split(",|，|、");
			for (String item : texts) {
				result.add(item.trim());
			}
		}
		return result;
	}

	/**
	 * 实体类转Map
	 * 
	 * @param object
	 * @return
	 */
	public static Map<String, Object> entityToMap(Object object) {
		Map<String, Object> map = new HashMap();
		for (Field field : object.getClass().getDeclaredFields()) {
			try {
				boolean flag = field.isAccessible();
				field.setAccessible(true);
				Object o = field.get(object);
				map.put(field.getName(), o);
				field.setAccessible(flag);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	/**
	 * Map转实体类
	 * 
	 * @param map    需要初始化的数据，key字段必须与实体类的成员名字一样，否则赋值为空
	 * @param entity 需要转化成的实体类
	 * @return
	 */
	public static <T> T mapToEntity(Map<String, Object> map, Class<T> entity) {
		T t = null;
		try {
			t = entity.newInstance();
			for (Field field : entity.getDeclaredFields()) {
				if (map.containsKey(field.getName())) {
					boolean flag = field.isAccessible();
					field.setAccessible(true);
					Object object = map.get(field.getName());
					if (object != null && field.getType().isAssignableFrom(object.getClass())) {
						field.set(t, object);
					}
					field.setAccessible(flag);
				}
			}
			return t;
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t;
	}

	/**
	 * 编码
	 * 
	 * @param bytes
	 * @return
	 */
	public static String encode(byte[] bytes) {
		return Base64.getEncoder().encodeToString(bytes);
	}

	/**
	 * 解码
	 * 
	 * @param src
	 * @return
	 */
	public static byte[] decode(String src) {
		return Base64.getDecoder().decode(src);
	}

	/**
	 * 文件转64位编码
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String fileToBase64(MultipartFile file) throws Exception {
		String base64Image = Base64.getEncoder().encodeToString(file.getBytes());
		return base64Image;
	}

	/**
	 * 文件转64位编码
	 * 
	 * @param imageFile
	 * @return
	 * @throws Exception
	 */
	public static String fileToBase64(File imageFile) throws Exception {
		String base64Image = "";
		FileInputStream imageInFile = new FileInputStream(imageFile);
		// Reading a Image file from file system
		byte imageData[] = new byte[(int) imageFile.length()];
		imageInFile.read(imageData);
		base64Image = Base64.getEncoder().encodeToString(imageData);
		return base64Image;
	}

	/**
	 * 文件格式互转
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static File multipartFileToFile(MultipartFile file) throws Exception {

		File toFile = null;

		if (file.getSize() <= 0) {

			file = null;

		} else {

			InputStream ins = null;

			ins = file.getInputStream();

			toFile = new File(file.getOriginalFilename());

			inputStreamToFile(ins, toFile);

			ins.close();

		}

		return toFile;

	}

	/**
	 * 文件格式互转
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static File multipartFileToFile(String filePath, MultipartFile file) throws Exception {

		File toFile = null;

		if (file.getSize() <= 0) {

			file = null;

		} else {

			InputStream ins = null;

			ins = file.getInputStream();

			toFile = new File(filePath);

			inputStreamToFile(ins, toFile);

			ins.close();

		}

		return toFile;

	}

	public static void inputStreamToFile(InputStream ins, File file) {

		try {

			OutputStream os = new FileOutputStream(file);

			int bytesRead = 0;

			byte[] buffer = new byte[8192];

			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {

				os.write(buffer, 0, bytesRead);

			}

			os.close();

			ins.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	/**
	 * 
	 * @param bytes
	 * @param charsetName
	 * @return
	 * @throws Exception
	 */
	public static String bytesToString(byte[] bytes, String charsetName) throws Exception {
		String result = new String(bytes, charsetName);
		return result;
	}

	/**
	 * String转byte[]
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] stringToBytes(String str) {
		byte[] bytes = str.getBytes();
		return bytes;

	}

	/**
	 * InputStream转String
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public static String inputStreamToString(InputStream inputStream, String charsetName) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int bufferSize = 1024;
		byte[] data = new byte[bufferSize];
		int count = -1;
		while ((count = inputStream.read(data, 0, bufferSize)) != -1) {
			outputStream.write(data, 0, count);
			data = null;
		}
		return new String(outputStream.toByteArray(), charsetName);

	}

	/**
	 * String转InputStream
	 * 
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static InputStream stringToInputStream(String str, String charsetName) throws Exception {
		ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes(charsetName));
		return inputStream;

	}

	/**
	 * InputStream转Byte[]
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] inputStreamToBytes(InputStream inputStream) throws Exception {
		BufferedInputStream bufin = new BufferedInputStream(inputStream);
		int buffSize = 1024;
		ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);

		// System.out.println("Available bytes:" + in.available());

		byte[] temp = new byte[buffSize];
		int size = 0;
		while ((size = bufin.read(temp)) != -1) {
			out.write(temp, 0, size);
		}
		bufin.close();

		byte[] content = out.toByteArray();
		return content;

	}

	/**
	 * byte[]转InputStream
	 * 
	 * @param bytes
	 * @return
	 * @throws Exception
	 */
	public static InputStream bytesToInputStream(byte[] bytes) throws Exception {
		ByteArrayInputStream is = new ByteArrayInputStream(bytes);
		return is;
	}

	public static String listToString(List list, String string) {
		return StringUtils.join(list.toArray(), string);
	}

	public static byte[] getBytesByFile(File file) {
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			byte[] data = bos.toByteArray();
			bos.close();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static File multipartFileToFile(File folder, MultipartFile file) {

		if (!folder.exists()) {
			folder.mkdirs();
		}
		String name = file.getOriginalFilename();

		String filePath = folder.getAbsolutePath() + File.separator + name;

		File toFile = new File(filePath);

		InputStream ins;
		try {
			ins = file.getInputStream();

			inputStreamToFile(ins, toFile);

		} catch (IOException e) {

			e.printStackTrace();
		}

		return toFile;

	}

	public static String convertByteSize(int size) {
		// 获取到的size为：1705230
		int GB = 1024 * 1024 * 1024;// 定义GB的计算常量
		int MB = 1024 * 1024;// 定义MB的计算常量
		int KB = 1024;// 定义KB的计算常量
		DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
		String resultSize = "";
		if (size / GB >= 1) {
			// 如果当前Byte的值大于等于1GB
			resultSize = df.format(size / (float) GB) + "GB";
		} else if (size / MB >= 1) {
			// 如果当前Byte的值大于等于1MB
			resultSize = df.format(size / (float) MB) + "MB";
		} else if (size / KB >= 1) {
			// 如果当前Byte的值大于等于1KB
			resultSize = df.format(size / (float) KB) + "KB";
		} else {
			resultSize = size + "B";
		}
		return resultSize;
	}

	public static String changeMean(String str) {
		String str1 = "*.?+$^[](){}|\\/";
		StringBuffer sf = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			String ss = String.valueOf(str.charAt(i));
			if (str1.contains(ss)) {
				ss = "\\" + ss;
			}
			sf.append(ss);
		}
		return sf.toString();
	}

	public static String mapToString(Map<String, String> map) {
		String str = "";
		if (map == null) {
			return str;
		}
		for (String key : map.keySet()) {
			str += key + "：" + map.get(key) + "；";
		}
		return str;
	}
}
